<?php


namespace App\Http\Controllers;


use App\Models\Weather;
use App\Server\Constants;
use App\Server\TencentMap;
use Illuminate\Http\Request;

/**
 * 天气
 * Class WeatherController
 * @package App\Http\Controllers
 */
class WeatherController extends Controller
{

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Throwable
     */
    public function index(Request $request)
    {
        $city = $request->city;
        if (!$request->city) {
            $city = 'nankang';
            if ($request->lat) {
                $location = $request->lat . ',' . $request->lng;
                $city = TencentMap::locationCity($location);
            }
        }

        $data = Weather::where('city', $city)->orderByDesc('id')->limit(3)->get()->toArray();
        $data = array_reverse($data);
        $data = array_values($data);

        foreach ($data as $k => &$item) {
            $item['date'] = $k == 0 ? '今天' : ($k == 1 ? '明天' : '后天');
            //修正钓鱼建议
            if ($item['wind_power'] <= 2) {
                $item['proposal'] = str_replace(['风太大了，'], '', $item['proposal']);
            }
            unset($item['created_at'], $item['updated_at'], $item['deleted_at']);
        }

        //后天的数据没有，则补齐
        if (count($data) < 3) {
            $item = [
                "city" => $request->city,
                "city_name" => Constants::$city[$request->city],
                "weather" => "/",
                "temperature" => "/",
                "evaluate" => "数据读取中...",
                "proposal" => "数据读取中...",
                "wind_direction" => "/",
                "wind_power" => "/",
                "pressure" => "/",
                "score" => 60,
                "bg_color" => "warning",
                "date" => "2022-03-22",
            ];
            $data[] = $item;
        }
        return $this->success($data);
    }
}